
package com.linkelee.server.controller.sys;

import com.linkelee.api.annotation.SysLogSave;
import com.linkelee.api.constant.SysConstants;
import com.linkelee.api.model.base.JsonResult;
import com.linkelee.api.model.sys.SysRole;
import com.linkelee.api.service.sys.ISysRoleMenuService;
import com.linkelee.api.service.sys.ISysRoleService;
import com.linkelee.api.util.PageUtils;
import com.linkelee.api.util.ValidatorUtils;
import com.linkelee.server.controller.base.AbstractController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色管理
 *
 * @author lsl 154751575@qq.com
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends AbstractController {
	@Autowired
	private ISysRoleService sysRoleService;
	@Autowired
	private ISysRoleMenuService sysRoleMenuService;

	/**
	 * 角色列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("sys:role:list")
	public JsonResult list(@RequestParam Map<String, Object> params){
		//如果不是超级管理员，则只查询自己创建的角色列表
		if(getUserId() != SysConstants.SUPER_ADMIN){
			params.put("createUserId", getUserId());
		}

		PageUtils page = sysRoleService.queryPage(params);

		return JsonResult.ok().put("page", page);
	}
	
	/**
	 * 角色列表
	 */
	@GetMapping("/select")
	@RequiresPermissions("sys:role:select")
	public JsonResult select(){
		Map<String, Object> map = new HashMap<>();
		
		//如果不是超级管理员，则只查询自己所拥有的角色列表
		if(getUserId() != SysConstants.SUPER_ADMIN){
			map.put("create_user_id", getUserId());
		}
		List<SysRole> list = (List<SysRole>) sysRoleService.listByMap(map);
		
		return JsonResult.ok().put("list", list);
	}
	
	/**
	 * 角色信息
	 */
	@GetMapping("/info/{roleId}")
	@RequiresPermissions("sys:role:info")
	public JsonResult info(@PathVariable("roleId") Long roleId){
		SysRole role = sysRoleService.getById(roleId);
		
		//查询角色对应的菜单
		List<Long> menuIdList = sysRoleMenuService.queryMenuIdList(roleId);
		role.setMenuIdList(menuIdList);
		
		return JsonResult.ok().put("role", role);
	}
	
	/**
	 * 保存角色
	 */
	@SysLogSave("保存角色")
	@PostMapping("/save")
	@RequiresPermissions("sys:role:save")
	public JsonResult save(@RequestBody SysRole role){
		ValidatorUtils.validateEntity(role);
		role.setCreateUserId(getUserId());
		sysRoleService.saveRole(role);
		
		return JsonResult.ok();
	}
	
	/**
	 * 修改角色
	 */
	@SysLogSave("修改角色")
	@PostMapping("/update")
	@RequiresPermissions("sys:role:update")
	public JsonResult update(@RequestBody SysRole role){
		ValidatorUtils.validateEntity(role);
		role.setCreateUserId(getUserId());
		sysRoleService.update(role);
		
		return JsonResult.ok();
	}
	
	/**
	 * 删除角色
	 */
	@SysLogSave("删除角色")
	@PostMapping("/delete")
	@RequiresPermissions("sys:role:delete")
	public JsonResult delete(@RequestBody Long[] roleIds){
		sysRoleService.deleteBatch(roleIds);
		
		return JsonResult.ok();
	}
}
